const Base = require('./base.js');
const moment = require('moment');
const md5 = require('md5');
const password_salt='HIOLABS';
module.exports = class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexStoreAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'id';
        const name = this.get('name') || '';
        let seachdata = { }, timesearch = {};
        if (name) {
            seachdata.name = ['like', `%${name}%`];
        }

        const model = this.model('store');
        const data = await model.where(
            seachdata
        ).order([sortField]).page(page, size).countSelect();
        return this.success(data);
    }

    //新增门店
    async saveStoreAction() {
        const model = this.model('store');
        let values = this.post();
        let id = this.post('id')||0;
        values['admin_id']=think.userId;
        values['update_time']=Math.floor(new Date().getTime()/1000);
        if (id>0) {
            id=await model.where({ id: id }).update(values);
        } else {
            values['id']=0;
            const old =await model.where({ name:values['name'] }).find();
            if(!think.isEmpty(old)){
                return this.fail(400,'该门店名已存在');
            }
            id = await model.add(values);
            values['id'] = id;
        }
        return this.success(values);
    }
    async updateStoreAction() {
        const model = this.model('store');
        const values = this.post();
        values['admin_id']=think.userId;
        values['update_time']=Math.floor(new Date().getTime()/1000);
        const id = this.post('id');
        const old =await model.where({ id: ['<>',id],name:values['name']}).find();
        if(!think.isEmpty(old)){
            return this.fail(400,'该门店名已存在');
        }
        let data = await model.where({id: id}).update(values);
        return this.success(data);
    }

    async readStoreAction() {
        const model = this.model('store');
        const id = this.get('id');
        const data=await model.where({id: id}).find();
        return this.success(data);
    }

    async deleteStoreAction() {
        const model = this.model('store');
        const id = this.post('id');
        const storeUser = await this.model('admin').where({site_id:id,is_delete:0}).select();
        if(!think.isEmpty(storeUser)){
            return this.fail(400,'含有业务员，请先删除所有的业务员，再删除门店');
        }
        let data = await model.where({ id: id }).delete();
        return this.success(data);
    }
    async saleManListAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'id';
        const model = this.model('store');
        const id = this.get('id');
        const storeUser = await this.model('saleman').where('is_delete=0 and FIND_IN_SET('+id+',site_id)').order([sortField]).page(page, size).countSelect();
        return this.success(storeUser);
    }

    async indexRoleAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'id';
        const name = this.get('name') || '';
        let seachdata = { }, timesearch = {};
        if (name) {
            seachdata.role_name = ['like', `%${name}%`];
        }

        const model = this.model('role');
        const data = await model.where(
            seachdata
        ).order([sortField]).page(page, size).countSelect();
        return this.success(data);
    }
    //新增权限组
    async saveRoleAction() {
        const model = this.model('role');
        let values = this.post();
        let id = this.post('id')||0;
        values['admin_id']=think.userId;
        values['update_time']=Math.floor(new Date().getTime()/1000);
        if (id>0) {
            id=await model.where({ id: id }).update(values);
        } else {
            values['id']=0;
            const old =await model.where({ role_name:values['role_name']}).find();
            if(!think.isEmpty(old)){
                return this.fail(400,'该权限组已存在');
            }
            id = await model.add(values);
            values['id'] = id;
        }
        return this.success(values);
    }
    async updateRoleAction() {
        const model = this.model('role');
        const values = this.post();
        values['admin_id']=think.userId;
        values['update_time']=Math.floor(new Date().getTime()/1000);
        const id = this.post('id');
        const old =await model.where({ id:['<>',id],role_name:values['role_name']}).find();
            if(!think.isEmpty(old)){
                return this.fail(400,'该权限组已存在');
            }
        let data = await model.where({id: id}).update(values);
        return this.success(data);
    }

    async readRoleAction() {
        const model = this.model('role');
        const id = this.get('id');
        const data=await model.where({id: id}).find();
        return this.success(data);
    }

    async deleteRoleAction() {
        const model = this.model('role');
        const id = this.post('id');
        const storeUser = await this.model('admin').where({role_id:id,is_delete:0}).select();
        if(!think.isEmpty(storeUser)){
            return this.fail(400,'含有业务员，请先删除所有的业务员，再删除权限组');
        }
        let data = await model.where({ id: id }).delete();
        return this.success(data);
    }

    //业务员
    async indexSalemanAction() {
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const sortField = this.get('sortfield') || 'id';
        const name = this.get('name') || '';
        const nickname = this.get('nickname') || '';
        let seachdata = { 'hiolabs_saleman.is_delete':0}, timesearch = {};
        if (name) {
            seachdata['hiolabs_saleman.username'] = ['like', `%${name}%`];
        }
        if (nickname) {
            seachdata['hiolabs_saleman.nickname'] = ['like', `%${nickname}%`];
        }

        const model = this.model('saleman');
        const data = await model.join({ table: 'role',  join: 'left',as:'tr',on: ['role_id', 'id'] })
        .where(
            seachdata
        ).field('hiolabs_saleman.*,tr.role_name').order([sortField]).page(page, size).countSelect();
        for(const item of data.data){
            item.password='';
            item.password_salt='';
            item.store_ids=item.site_id.split(',');
            if(item.store_ids.length<1) item.store_ids=[0];
            item.storeText=(await this.model('store').where({id:['IN',item.store_ids]}).getField('name')).join(',');
        }
        return this.success(data);
    }
     
     async saveSalemanAction() {
        const model = this.model('saleman');
        let values = this.post();
        let password = this.post('password');
        let confirmpassword = this.post('confirmpassword');
        let store_ids = this.post('store_ids');
        let id = this.post('id')||0;
        values['register_time']=Math.floor(new Date().getTime()/1000);
        values['site_id'] = store_ids.join(',');
        values['password_salt'] = password_salt;
        if (id>0) {
            return this.fail(400,'无效参数id');
        } else {
            values['id']=0;
            if(password!=confirmpassword){
                return this.fail(400,'两次输入的密码不一致');
            }
            const old =await model.where({ username:values['username'],is_delete:0}).find();
            if(!think.isEmpty(old)){
                return this.fail(400,'该账户已存在，勿添加重复的账户名');
            }
            if (password.replace(/(^\s*)|(\s*$)/g, "").length != 0) {
                values['password'] = md5(password + '' + password_salt);
            }else{
                return this.fail(400,'空密码！');
            }
            id = await model.add(values);
            values['id'] = id;
        }
        return this.success();
    }
    async updateSalemanAction() {
        const model = this.model('saleman');
        const values = this.post();
        let password = this.post('password');
        let confirmpassword = this.post('confirmpassword');
        let store_ids = this.post('store_ids');
        values['register_time']=Math.floor(new Date().getTime()/1000);
        values['site_id'] = store_ids.join(',');
        values['password_salt'] = password_salt;
        const id = this.post('id');
        if(password!=confirmpassword){
            return this.fail(400,'两次输入的密码不一致');
        }
        if(password.replace(/(^\s*)|(\s*$)/g, "").length == 0){
            delete values.password;
        }else{
            values.password = md5(password + '' + password_salt);
        }
        const old =await model.where({ id:['<>',id],username:values['username'],is_delete:0}).find();
            if(!think.isEmpty(old)){
                return this.fail(400,'该账户已存在，勿添加重复的账户名');
            }
        let data = await model.where({id: id}).update(values);
        return this.success();
    }

    async readSalemanAction() {
        const model = this.model('saleman');
        const id = this.get('id');
        const data=await model.where({'hiolabs_saleman.id': id}).join({ table: 'role',  join: 'left',as:'tr',on: ['role_id', 'id'] })
        .field('hiolabs_saleman.*,tr.role_name').find();
        data.store_ids=data.site_id.split(',');
        if(data.store_ids.length<1) data.store_ids=[0];
        data.storeText=(await this.model('store').where({id:['IN',data.store_ids]}).getField('name')).join(',');
        data.password='';
        data.password_salt='';
        return this.success(data);
    }

    async deleteSalemanAction() {
        const model = this.model('saleman');
        const id = this.post('id');
        let data = await model.where({ id: id }).update({is_delete:1});
        return this.success(data);
    }
   
    
    

    /**
     * 商家设置
     */
    async merchantSetAction() {//
        let values = this.post();
        let basic = this.post('basic');
        let ad = this.post('advertising');
        let active = this.post('active');
        let other = this.post('other');
        const model = this.model('setmodel');
        const bdata = await model.where({setmodel:'storeBasic'}).find(); 
        const addata = await model.where({setmodel:'storeAd'}).find(); 
        const activedata = await model.where({setmodel:'storeActive'}).find(); 
        const odata = await model.where({setmodel:'storeOther'}).find();
        let now=Math.floor(new Date().getTime()/1000);
        let basicdata={
            setmodel:'storeBasic',
            setting:JSON.stringify(basic),
            user_id:think.userId,
            update_time:now
        }
        if(think.isEmpty(bdata)){
            await model.add(basicdata);
        }else{
            await model.where({setmodel:'storeBasic'}).update(basicdata);
        }
        let advertisingdata={
            setmodel:'storeAd',
            setting:JSON.stringify(ad),
            user_id:think.userId,
            update_time:now
        }
        if(think.isEmpty(addata)){
            await model.add(advertisingdata);
        }else{
            await model.where({setmodel:'storeAd'}).update(advertisingdata);
        }
        let activeset={
            setmodel:'storeActive',
            setting:JSON.stringify(active),
            user_id:think.userId,
            update_time:now
        }
        if(think.isEmpty(activedata)){
            await model.add(activeset);
        }else{
            await model.where({setmodel:'storeActive'}).update(activeset);
        }
        let otherset={
            setmodel:'storeOther',
            setting:JSON.stringify(other),
            user_id:think.userId,
            update_time:now
        }
        if(think.isEmpty(odata)){
            await model.add(otherset);
        }else{
            await model.where({setmodel:'storeOther'}).update(otherset);
        }

        return this.success(values);
    }
    async getMerchantSetAction() {//获取
        const model = this.model('setmodel');
        const bdata = await model.where({setmodel:'storeBasic'}).find(); 
        const addata = await model.where({setmodel:'storeAd'}).find(); 
        const activedata = await model.where({setmodel:'storeActive'}).find(); 
        const odata = await model.where({setmodel:'storeOther'}).find();
        let r={};
        if(think.isEmpty(bdata)){
            r.basicData={};
        }else{
            r.basicData=JSON.parse(bdata.setting);
        }
        if(think.isEmpty(addata)){
            r.adData={};
        }else{
            r.adData=JSON.parse(addata.setting);
        }
        if(think.isEmpty(activedata)){
            r.activeData={};
        }else{
            r.activeData=JSON.parse(activedata.setting);
        }
        if(think.isEmpty(odata)){
            r.otherData={};
        }else{
            r.otherData=JSON.parse(odata.setting);
        }

        return this.success(r);
    }



      

};